// 全局 G2 设置
import { track, setTheme, Shape, G2 } from 'bizcharts';
import { commonConfig } from './config';

const { defaultColor } = commonConfig;
track(false);

const config = {
  defaultColor,
  shape: {
    interval: {
      fillOpacity: 1,
    },
  },
};

setTheme(config);

const { Util } = G2;
const getFillAttrs = cfg => {
  const attrs = Util.mix(cfg.style, {
    fill: cfg.color,
    fillOpacity: cfg.opacity,
  });
  return attrs;
};
const getRectPath = points => {
  const path = [];
  for (let i = 0; i < points.length; i++) {
    const point = points[i];
    if (point) {
      const action = i === 0 ? 'M' : 'L';
      path.push([action, point.x, point.y]);
    }
  }
  const first = points[0];
  path.push(['L', first.x, first.y]);
  path.push(['z']);
  return path;
};
// 带圆角路径
Shape.registerShape('interval', 'circleBar', {
  draw(cfg, container) {
    const attrs = getFillAttrs(cfg);
    let path = getRectPath(cfg.points);
    path = this.parsePath(path); // 将 0 - 1 的值转换为画布坐标
    let radius = (path[2][1] - path[1][1]) / 2;
    const temp = [];
    const differY = path[0][2] - path[1][2];
    if (isNaN(differY) || differY >= 0) {
      if (path[0][2] - path[1][2] < radius) radius = path[0][2] - path[1][2]; // 数值过小时的处理
      temp.push(['M', path[0][1], path[0][2]]);
      temp.push(['L', path[1][1], path[1][2] + radius]);
      temp.push(['A', radius, radius, 90, 0, 1, path[1][1] + radius, path[1][2]]);
      temp.push(['L', path[2][1] - radius, path[2][2]]);
      temp.push(['A', radius, radius, 90, 0, 1, path[2][1], path[2][2] + radius]);
      temp.push(['L', path[3][1], path[3][2]]);
      temp.push(['Z']);
    } else {
      if (path[1][2] - path[0][2] < radius) radius = path[1][2] - path[0][2]; // 数值过小时的处理
      temp.push(['M', path[0][1], path[0][2]]);
      temp.push(['L', path[1][1], path[1][2] - radius]);
      temp.push(['A', radius, radius, 90, 0, 0, path[1][1] + radius, path[1][2]]);
      temp.push(['L', path[2][1] - radius, path[2][2]]);
      temp.push(['A', radius, radius, 90, 0, 0, path[2][1], path[2][2] - radius]);
      temp.push(['L', path[3][1], path[3][2]]);
      temp.push(['Z']);
    }
    return container.addShape('path', {
      attrs: Util.mix(attrs, {
        path: temp,
      }),
    });
  },
});
